/** 封装http请求 */
import axios from 'axios'
import Router from '../router/index'
import { Message } from 'element-ui'
import { setToken, getToken } from '@/utils/cookie.ts'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    timeout: 5000
})

// Request interceptors
service.interceptors.request.use(
    config => {
        // 为每一个请求添加时间戳
        if (config.method === 'post') {
            config.params = {
                cd: Date.parse(new Date() as any) / 1000
            }
        } else if (config.method === 'get') {
            config.params = {
                cd: Date.parse(new Date() as any) / 1000,
                ...config.params
            }
        }

        /** 并且每一次进行都会将token的过期时间改变 */
        setToken(getToken())

        config.headers['X-Requested-With'] = 'XMLHttpRequest'
        return config
    },
    error => {
        Promise.reject(error)
    }
)

// Response interceptors
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code === 403) {
            // 保护user获取
            if (response.config.url?.includes('/user')) {
                return res
            }
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 3 * 1000
            })
            Router.push('/login')
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
    },
    error => {
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
